package malohlava.apps.mendeley.scribe.extractors;

import java.util.regex.*;

import org.scribe.exceptions.*;
import org.scribe.model.*;
import org.scribe.extractors.*;
import org.scribe.utils.*;

/**
* Default implementation of {@RequestTokenExtractor} and {@AccessTokenExtractor}. Conforms to OAuth 1.0a
*
* The process for extracting access and request tokens is similar so this class can do both things.
*
* @author Pablo Fernandez
*/
public class ImprovedTokenExtractorImpl implements RequestTokenExtractor, AccessTokenExtractor
{
  /* Pattern regex modified to accept oauth_callback_accepted */
  private static final String TOKEN_REGEX = "oauth_callback_accepted=1&oauth_token=(\\S*)&oauth_token_secret=(\\S*?)(&(.*))?";

  /**
   * {@inheritDoc}
   */
  public Token extract(String response)
  {
    Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");

    System.out.println("RESPONSE: " + response);

    Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response);
    if (matcher.matches())
    {
      String token = URLUtils.percentDecode(matcher.group(1));
      String secret = URLUtils.percentDecode(matcher.group(2));
      return new Token(token, secret);
    } else
    {
      throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
    }
  }
}

